﻿using DevExpress.XtraEditors;
using MesProjectWinform.BasicData.Entity;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.BasicData.基础实现.gongyings
{
    public partial class ying : DevExpress.XtraEditors.XtraForm
    {
        // 分页参数
        private int pageIndex = 1;
        private int pageSize = 4;
        private int totalCount = 0;

        public ying()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化分页控件
            InitPagination();
            
            // 初始化时加载数据
            LoadData();
        }
        
        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPagination()
        {
            // 创建页大小下拉框
            ComboBoxEdit pageSizeCombo = new ComboBoxEdit();
            pageSizeCombo.Properties.Items.AddRange(new object[] { 4, 10, 20, 50, 100 });
            pageSizeCombo.SelectedIndex = 0;
            pageSizeCombo.Width = 60;
            pageSizeCombo.EditValueChanged += PageSizeCombo_EditValueChanged;
            
            // 创建首页按钮
            SimpleButton btnFirst = new SimpleButton();
            btnFirst.Text = "首页";
            btnFirst.Width = 60;
            btnFirst.Click += BtnFirst_Click;
            
            // 创建尾页按钮
            SimpleButton btnLast = new SimpleButton();
            btnLast.Text = "尾页";
            btnLast.Width = 60;
            btnLast.Click += BtnLast_Click;
            
            // 创建页码标签
            LabelControl lblPageInfo = new LabelControl();
            lblPageInfo.Name = "lblPageInfo";
            lblPageInfo.Text = "0/0";
            lblPageInfo.AutoSize = true;
            lblPageInfo.Padding = new Padding(5, 3, 5, 0);
            
            // 创建总记录数标签
            LabelControl lblTotalCount = new LabelControl();
            lblTotalCount.Name = "lblTotalCount";
            lblTotalCount.Text = "共0条记录";
            lblTotalCount.AutoSize = true;
            lblTotalCount.Padding = new Padding(5, 3, 5, 0);
            
            // 创建页大小标签
            LabelControl lblPageSize = new LabelControl();
            lblPageSize.Text = "每页显示:";
            lblPageSize.AutoSize = true;
            lblPageSize.Padding = new Padding(5, 3, 5, 0);
            
            // 添加控件到窗体底部
            FlowLayoutPanel paginationPanel = new FlowLayoutPanel();
            paginationPanel.Dock = DockStyle.Bottom;
            paginationPanel.Height = 40;
            paginationPanel.Padding = new Padding(5);
            paginationPanel.FlowDirection = FlowDirection.LeftToRight;
            
            // 添加控件到面板
            paginationPanel.Controls.Add(btnFirst);
            paginationPanel.Controls.Add(button3); // 上一页按钮
            paginationPanel.Controls.Add(lblPageInfo);
            paginationPanel.Controls.Add(button4); // 下一页按钮
            paginationPanel.Controls.Add(btnLast);
            paginationPanel.Controls.Add(lblTotalCount);
            paginationPanel.Controls.Add(lblPageSize);
            paginationPanel.Controls.Add(pageSizeCombo);
            
            // 添加面板到窗体
            this.Controls.Add(paginationPanel);
            
            // 调整原有按钮宽度和样式
            button3.Width = 60;
            button3.Text = "上一页";
            button4.Width = 60;
            button4.Text = "下一页";
        }
        
        /// <summary>
        /// 页大小改变事件
        /// </summary>
        private void PageSizeCombo_EditValueChanged(object sender, EventArgs e)
        {
            ComboBoxEdit combo = sender as ComboBoxEdit;
            if (combo != null && int.TryParse(combo.EditValue.ToString(), out int newPageSize))
            {
                pageSize = newPageSize;
                pageIndex = 1; // 重置为第一页
                LoadData();
            }
        }
        
        /// <summary>
        /// 首页按钮点击事件
        /// </summary>
        private void BtnFirst_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex = 1;
                LoadData();
            }
        }
        
        /// <summary>
        /// 尾页按钮点击事件
        /// </summary>
        private void BtnLast_Click(object sender, EventArgs e)
        {
            int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            if (pageIndex < totalPages)
            {
                pageIndex = totalPages;
                LoadData();
            }
        }

        /// <summary>
        /// 加载供应商数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 构建查询URL
                string url = $"api/Supplier/GetSupplier?pageindex={pageIndex}&pagesize={pageSize}";
                
                if (!string.IsNullOrEmpty(textEdit1.Text))
                    url += $"&suppliercode={textEdit1.Text.Trim()}";
                
                if (!string.IsNullOrEmpty(textEdit2.Text))
                    url += $"&suppliername={textEdit2.Text.Trim()}";

                // 临时保存原始BaseUrl
                string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                try
                {
                    // 临时修改BaseUrl为端口5052
                    Properties.Settings.Default.BaseUrl = "http://47.110.243.157:5052/";
                    
                    // 发送请求
                    string result = await HttpClientHelper.RequestUrl(RequestType.Get, url, string.Empty);
                    if (string.IsNullOrEmpty(result))
                    {
                        XtraMessageBox.Show("获取数据失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 解析数据
                    JObject jsonObj = JObject.Parse(result);
                    if (jsonObj["Code"]?.ToString() != "200")
                    {
                        XtraMessageBox.Show(jsonObj["Message"]?.ToString() ?? "请求失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    // 处理数据
                    JArray pageData = jsonObj["PageData"] as JArray;
                    if (pageData != null && pageData.Count > 0)
                    {
                        // 显示数据
                        gridControl1.DataSource = pageData.ToObject<List<SupplierModel>>();
                        totalCount = jsonObj["TotalCount"]?.Value<int>() ?? 0;
                    }
                    else
                    {
                        // 无数据
                        gridControl1.DataSource = null;
                        totalCount = 0;
                        XtraMessageBox.Show("没有查询到符合条件的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    
                    // 更新页码信息
                    UpdatePageInfo();
                }
                finally
                {
                    // 恢复原始BaseUrl
                    Properties.Settings.Default.BaseUrl = originalBaseUrl;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新页码信息
        /// </summary>
        private void UpdatePageInfo()
        {
            int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            
            // 更新为简单标题，不包含页码信息
            this.Text = "供应商管理";

            // 更新分页信息标签
            LabelControl lblPageInfo = this.Controls.Find("lblPageInfo", true).FirstOrDefault() as LabelControl;
            if (lblPageInfo != null)
            {
                lblPageInfo.Text = $"{pageIndex}/{totalPages}";
            }
            
            // 更新总记录数标签
            LabelControl lblTotalCount = this.Controls.Find("lblTotalCount", true).FirstOrDefault() as LabelControl;
            if (lblTotalCount != null)
            {
                lblTotalCount.Text = $"共{totalCount}条记录";
            }
            
            // 设置按钮状态
            SimpleButton btnFirst = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "首页");
            SimpleButton btnLast = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "尾页");
            
            if (btnFirst != null) btnFirst.Enabled = pageIndex > 1;
            if (btnLast != null) btnLast.Enabled = pageIndex < totalPages;
            button3.Enabled = pageIndex > 1;
            button4.Enabled = pageIndex < totalPages;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.FocusedRowHandle >= 0)
                {
                    // 获取当前行的供应商对象
                    SupplierModel supplier = view.GetRow(view.FocusedRowHandle) as SupplierModel;
                    if (supplier != null)
                    {
                        // 打开修改窗口并传递ID
                        yingup updateForm = new yingup(supplier.Id);
                        if (updateForm.ShowDialog() == DialogResult.OK)
                        {
                            // 窗口关闭后刷新数据
                            LoadData();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开修改窗口失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.FocusedRowHandle >= 0)
                {
                    // 获取当前行的供应商对象
                    SupplierModel supplier = view.GetRow(view.FocusedRowHandle) as SupplierModel;
                    if (supplier != null)
                    {
                        // 确认是否删除
                        DialogResult result = XtraMessageBox.Show($"确定要删除供应商 [{supplier.Suppliername}] 吗？", 
                            "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            
                        if (result == DialogResult.Yes)
                        {
                            // 构建删除URL
                            string url = $"api/Supplier/DeleteSupplier?id={supplier.Id}";
                            
                            // 临时保存原始BaseUrl
                            string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                            try
                            {
                                // 临时修改BaseUrl为端口5052
                                Properties.Settings.Default.BaseUrl = "http://47.110.243.157:5052/";
                                
                                // 发送删除请求
                                string response = await HttpClientHelper.RequestUrl(RequestType.Put, url, string.Empty);
                                
                                if (!string.IsNullOrEmpty(response))
                                {
                                    // 解析响应
                                    JObject jsonObj = JObject.Parse(response);
                                    if (jsonObj["Code"]?.ToString() == "200")
                                    {
                                        XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        // 删除成功后刷新当前页面
                                        LoadData();
                                    }
                                    else
                                    {
                                        XtraMessageBox.Show(jsonObj["Message"]?.ToString() ?? "删除失败", "错误", 
                                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    XtraMessageBox.Show("删除请求失败，请检查网络连接", "错误", 
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            finally
                            {
                                // 恢复原始BaseUrl
                                Properties.Settings.Default.BaseUrl = originalBaseUrl;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            // 创建新增窗口
            yingup addForm = new yingup();
            
            // 显示窗口并等待结果
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                // 如果窗口返回OK结果，说明添加成功，刷新数据
                LoadData();
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            pageIndex = 1; // 重置为第一页
            LoadData();
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                LoadData();
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            if (pageIndex < totalPages)
            {
                pageIndex++;
                LoadData();
            }
        }
    }
}